import { Controller } from 'egg';

export default class AuthController extends Controller {

  public async login() {
    const { ctx, app } = this
    const { user } = ctx.request.body
    // 通过传入的请求体中的username在数据库中查找实体
    const res: any = await ctx.service.user.selectByUsername(user.username)
    if (res.length > 0 && user.password === res[0].password) {
      // 生成token
      const token = app.jwt.sign({ username: user.username }, app.config.jwt.secret)

      ctx.body = {
        code: 2000,
        token,
        msg: '登录成功',
      }

    } else {
      ctx.body = {
        code: 4000,
        msg: '账号或密码错误'
      }
    }
  }

  public async register() {
    const { ctx } = this
    const { user } = ctx.request.body
    const res: any = await ctx.service.user.selectByUsername(user.username)
    if (res.length > 0) {
      // 表示数据库中已经有该用户名
      ctx.body = {
        code: 4000,
        msg: '用户名已经存在'
      }
    } else {
      // 将用户名存储到数据库中
      // 先设置初始值
      user.role = 'trainer'
      user.nickname = user.username
      await ctx.service.user.addOne(user)
      ctx.body = {
        code: 2000,
        msg: '注册成功'
      }
    }
  }

  public async getUserInfo() {
    const { ctx, app } = this
    // 拿到传会数据的header 中的token值
    const token = ctx.request.header.authorization;
    // 解码token
    const decode: any = await app.jwt.verify(token as any, app.config.jwt.secret);
    const userRes: any = await ctx.service.user.selectByUsername(decode['username'])
    const roleRes: any = await ctx.service.role.selectByRole(userRes[0].role)
    ctx.body = {
      code: 2000,
      nickname: userRes[0].nickname,
      role: roleRes[0].description
    }
  }
}
